<?php
class Ballot extends AppModel {

	var $name = 'Ballot';
	/*
	var $validate = array(
		'user_id' => array('rule' => 'numeric', 'required' => true, 'allowEmpty' => false),
		'date' => array('rule' => 'date', 'required' => true, 'allowEmpty' => false),
		'ballot_data' => array('rule' => 'notEmpty', 'required' => true, 'allowEmpty' => false)
	);*/
	
	var $ballotData;

	//The Associations below have been created with all possible keys, those that are not needed can be removed
	var $belongsTo = array(
		'User' => array(
			'className' => 'User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

	function findSavedBallot($user_id, $zip, $plus4, $voteDate) {
		return $this->find('first', 
      array('conditions' => array('Ballot.user_id' => $user_id, 
                                 'Ballot.zip' => $zip, 
                                 'Ballot.plus4' => $plus4,
                                 'Ballot.vote_date' => $voteDate)));
	}
	
	function saveBallotData($user_id, $ballotData) {
    $this->create();
    $savedData = $this->findSavedBallot($user_id, 
                          $ballotData['zip'], $ballotData['plus4'], $ballotData['voteDate']);
    if (!empty($savedData)) {
    	$this->id = $savedData['Ballot']['id'];
    }
    $this->set('user_id', $user_id);
    $this->set('zip', $ballotData['zip']);
    $this->set('plus4', $ballotData['plus4']);
    $this->set('vote_date', $ballotData['voteDate']);
    $this->set('ballot_data', serialize($ballotData));
    if ($this->save()) {
    	return $this->id;
    }
    else {
    	return -1;
    }
	}
	
	function readBallotData($id) {
   	$ballotData = $this->read(null, $id);
    $ballotData['Ballot']['ballot_data'] = unserialize($ballotData['Ballot']['ballot_data']);
    return $ballotData;
	}
	
	function findLastestBallot($user_id) {
		$ballots = $this->findAllByUserId($user_id);
		if (!empty($ballots) || true) {
			$latestBallot = null;
			foreach ($ballots as $ballot) {
				if ($latestBallot == null) {
					$latestBallot = $ballot;
				}
				else if (strtotime($ballot['Ballot']['vote_date']) > strtotime($latestBallot['Ballot']['vote_date'])) {
					$latestBallot = $ballot;
				}
				else if (strtotime($ballot['Ballot']['vote_date']) == strtotime($latestBallot['Ballot']['vote_date']) && 
				strtotime($ballot['Ballot']['modified']) > strtotime($latestBallot['Ballot']['modified'])){
					$latestBallot = $ballot;
				}
	      else if (strtotime($ballot['Ballot']['vote_date']) == strtotime($latestBallot['Ballot']['vote_date']) && 
	      strtotime($ballot['Ballot']['created']) > strtotime($latestBallot['Ballot']['created'])){
	        $latestBallot = $ballot;
	      }
			}
			if (!empty($latestBallot)) {
			  return $this->readBallotData($latestBallot['Ballot']['id']);
			}
			return null;
		}
	}
}
?>